<?php 
ob_start();
session_start();
$xx=session_id();

?>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>adwebmob</title>
<script type="text/javascript">
        var GB_ROOT_DIR = "./greybox/";
</script>
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJS_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<script type="text/javascript" src="JavaScripts/jquery-1.4.2.min.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<?php
include("UserIncludes/DbConfig.php");
$fid=$_REQUEST['fid'];
define('DS',DIRECTORY_SEPARATOR);
//upload dirs
$dir_root=dirname(__FILE__).DS."campaign_upload".DS;
$dir_temp =$dir_root. $_SESSION[siteuserId].DS.'temp'.DS;
$dir =$dir_root. $_SESSION[siteuserId].DS;
$dir_temp_url="campaign_upload/".$_SESSION[siteuserId].'/temp/';
$dir_url="campaign_upload/".$_SESSION[siteuserId].'/';
if(!file_exists($dir_root))
	mkdir($dir_root);
if(!file_exists($dir))
	mkdir($dir);
if(!file_exists($dir_temp))
	mkdir($dir_temp);
if(!isset($_SESSION[siteuserId]) || $_SESSION[siteuserId]=='')
	echo '<script>window.location="index.php"</script>';


// Start Coming from popup
if(isset($_GET['form_id']) && $_GET['form_id'] != '')
{
$_SESSION['form_id'] = $_GET['form_id'];
}
// end coming from pop


if($_SESSION['langId']!="")
{
	$langId=$_SESSION['langId'];
}
else
{
	$langId="1";
}

// upload temp banner
if(isset($_POST['upload'])&&$_POST['upload']!='')
{
	//message 
	$msg=array();
	// validate flag 
	$validate =true;
	if ($_FILES["file"]["error"] > 0)
	{		
		$msg[]="Upload Error: Code ". $_FILES["file"]["error"];
		$validate=false;
	}
	else
	{
		//include image helpers
		include("UserIncludes/image.php");
		
		$file_name = $_FILES["file"]["name"];			
		$extension = explode('.',$file_name);  		
		$extension = $extension[count($extension)-1];
		// get allow banner file type 
		$banner_types = explode(',',BANNER_ACCEPT_TYPES);
		//validate image 		
		if(!in_array($extension,$banner_types))
		{
			$msg[]="Invalid file type. Only accept: ".implode(', ',$banner_types);
			$validate=false;
		}
		else
		{
			//get banner accept size
			$banner_sizes = explode(',',BANNER_SIZES);			
			$sizeBanner=cImageGetSize($_FILES['file']['tmp_name']);
			//$size = getimagesize($_FILES['file']['tmp_name']);
			// size objec to string dimension
			$sizeStr = $sizeBanner->width.'x'.$sizeBanner->height;
			//check banner size
			if(!in_array($sizeStr,$banner_sizes))
			{
				$validate=false;
				$msg[]="Dimension of banner must be: ".implode(', ',$banner_sizes);
			}
			
		}
	}
	if($validate)
	{
		
		$file_name_gent = md5(rand().time()).'.'.$extension;
		move_uploaded_file($_FILES['file']['tmp_name'],$dir_temp.$file_name_gent);		
		$banner_url = $dir_temp_url.$file_name_gent;		
		
	}
	else
	{
		echo "<script>alert('".implode('\n',$msg)."');</script>";
	}

}

// save
if(isset($_POST['addtocart']) && $_POST['addtocart'] != '')
{
	// validating 
	//flag
	$validate=true;
	$msg =array();
	$networkType = strtolower($_REQUEST['networkType']);	
	
	$banner_url = strip_tags($_POST['banner_url']);
	$dest_url = strip_tags($_POST['txtUrl']);
	$adName = strip_tags($_POST['txtAdName']);
	$adHeadLine = strip_tags($_POST['txtHeadline']);
	$description = strip_tags($_POST['text_description']);
	$groupId = $_GET['group_id'];
	if(empty($adHeadLine)&&($networkType=='thumbnail'))
	{
		$validate=false;
		$msg[]="Headline is missing";	
	}
	if(empty($banner_url)&&($networkType=='banner'||$networkType=='thumbnail'))
	{
		$validate=false;
		$msg[]="Banner is missing";	
	}
	if(empty($description)&&($networkType=='text'))
	{
		$validate=false;
		$msg[]="Description is missing";	
	}
	if(empty($dest_url))
	{
		$validate=false;
		$msg[]="Destination URL is missing";				
	}
	elseif(!strpos(' '.$dest_url,'http://')&& !strpos(' '.$dest_url,'https://'))
	{
		$validate=false;
		$msg[] = "Destination Url must be: http://sample.com";
	}
	if($validate)
	{	
		//get token
		$token = $_GET['token'];
		
		//	move template image into right directory
		/*$fileName = explode('/',$banner_url);
		$fileName = $fileName[count($fileName)-1];
		copy($dir_temp.DS.$fileName,$dir.DS.$fileName);*/
		// build right image url
		$banner_url= $_POST['banner_url'];
		// build query
		$garbage = 'garbage';
		if($_REQUEST['networkType']=='text')
		{		  
			$pop_query = "INSERT INTO temp_adgroup_ad(
				form_id,
				dest_url,
				personal_reference,
				garbage_val,
				siteuserId,
				networkId,
				networkType,			
				heading,
				ad_description,
				token,
				group_id)
			VALUES(
				'".$_SESSION['form_id']."',
				'".$dest_url."',
				'".$adName."',
				'".$garbage."',
				'".$_SESSION['siteuserId']."',
				'".$_REQUEST['networkId']."',
				'".$_REQUEST['networkType']."',			
				'".$adHeadLine."',
				'".$description."',
				'".$token."',
				'".$groupId."')" ;
		}
		else if($_REQUEST['networkType']=='thumbnail')
		{			
			$pop_query = "INSERT INTO temp_adgroup_ad(
				form_id,
				dest_url,
				personal_reference,
				garbage_val,
				siteuserId,
				networkId,
				networkType,
				upload_image,
				heading,
				token,
				group_id)
			VALUES(
				'".$_SESSION['form_id']."',
				'".$dest_url."',
				'".$adName."',
				'".$garbage."',
				'".$_SESSION['siteuserId']."',
				'".$_REQUEST['networkId']."',
				'".$_REQUEST['networkType']."',
				'".$banner_url."',
				'".$adHeadLine."',
				'".$token."',
				'".$groupId."')" ;
		}
		else if($_REQUEST['networkType']=='banner')
		{
			$pop_query = "INSERT INTO temp_adgroup_ad(
				form_id,
				dest_url,
				personal_reference,
				garbage_val,
				siteuserId,
				networkId,
				networkType,
				upload_image,
				token,
				group_id)
			VALUES(
				'".$_SESSION['form_id']."',
				'".$dest_url."',
				'".$adName."',
				'".$garbage."',
				'".$_SESSION['siteuserId']."',
				'".$_REQUEST['networkId']."',
				'".$_REQUEST['networkType']."',
				'".$banner_url."',
				'".$token."',
				'".$groupId."')" ;
		}		
		 $res = mysql_query($pop_query);

		$last_insert_id=mysql_insert_id();
		// delete all temp banner		
		/*$mydir = opendir($dir_temp);
		while(false !== ($file = readdir($mydir))) 
		{
			if($file != "." && $file != "..") 
			{
				@chmod($dir_temp.$file, 0777);
				if(is_dir($dir_temp.$file)) {
					@chdir('.');
					@destroy($dir_temp.$file.'/');
					@rmdir($dir_temp.$file) ;
				}
				else
					@unlink($dir_temp.$file);
			}
		}*/
		closedir($mydir);	
		// delete older template ad
		$inner_res = mysql_query("DELETE from temp_adgroup_ad where
		form_id = '".$_SESSION['form_id']."' AND siteuserId='".$_SESSION['siteuserId']."' AND token <> '$token'");
				
		$inner_res = mysql_query("select * from temp_adgroup_ad where
		form_id = '".$_SESSION['form_id']."' AND siteuserId='".$_SESSION['siteuserId']."' AND token='$token' AND group_id='$groupId'");
		$startTable = '<table align="center" width="90%" border="0" cellpadding="0" cellspacing="0" style="font-family: Arial; font-size: 12px; color: #000000;">';
		$endTable = '</table>';
		$i = 1;	
		if(mysql_num_rows($inner_res)>0)
		{	
			$rowStr .= '<input type="hidden" name="net_id'.$_REQUEST['fid'].'" id="net_id'.$_REQUEST['fid'].'" value='.$_REQUEST['networkId'].'>';
			$countinner_res =0;
			while($inner_row = mysql_fetch_array($inner_res))
			{
				$countinner_res++;
				$styleBr1  = '';
				if($countinner_res ==mysql_num_rows($inner_res))
				{
					$styleBr1 = 'border-bottom: 2px solid #4dc5d6;';
				}
				$rowStr .= '<tr class="ad-item"><td  width="40" height="30" align="center" style=" border-left: 2px solid #4dc5d6; border-right: 2px solid #4dc5d6; border-top: 2px solid #4dc5d6;'.$styleBr1.'">'.$i.'</td><td width="220" align="left" style="border-top: 2px solid #4dc5d6;border-right: 2px solid #4dc5d6;'.$styleBr1.'">'.$inner_row['personal_reference'].'&nbsp;</td> <td width="130" align="left" style="border-top: 2px solid #4dc5d6;'.$styleBr1.'">'.$inner_row['heading'].'&nbsp;</td><td align="left" style=" border-left: 2px solid #4dc5d6; border-right: 2px solid #4dc5d6; border-top: 2px solid #4dc5d6;'.$styleBr1.' padding-left: 5px;" width="40"><a href="javascript:void(0);" datafld="'.$inner_row[id].'" class="delete-ad" ><img alt="delete ad" src="images/delete.jpg" border="0"></a></td></tr>';
				$i++;
			}
			$finalResult = $startTable.$rowStr.$endTable;
			//echo $finalResult;
		}

		$SQL_total_ads="SELECT * from temp_adgroup_ad where
		form_id = '".$_SESSION['form_id']."' AND siteuserId='".$_SESSION['siteuserId']."' AND token = '$token' AND group_id='$groupId'";
		$EXE_total_ads=mysql_query($SQL_total_ads);		
		$total_ads=mysql_num_rows($EXE_total_ads);
	?>
		<script>
			
		top.document.getElementById('ad-area<?=$_GET['group_id']?>').innerHTML = '<?php echo $finalResult;?>' ;
		top.document.getElementById('no_of_ads').innerHTML = 'Ads: <?php echo $total_ads;?>' ;
		parent.parent.GB_hide();
		</script>
	<?php
	}
	else
	{
		//throw  error message
		echo "<script>alert('".implode('\n',$msg)."');</script>";
		
	}
}



// to get the type of ad query
$get_type_id = $_SESSION['type_id'] ; 
$res_type_query = mysql_query("select adspaceType from adspace_details where adspaceId = '".$get_type_id."' ");
$row_type_query = mysql_fetch_array($res_type_query);

if(isset($_POST['post_checking'])){
$adtype_retrieve=$_POST['network_type'];
}
else
$adtype_retrieve=$row_type_query['adspaceType'];
// End to get the type of ad query



?>
<script>

function main_page()
{
parent.parent.GB_hide();
}



function showhidSelectBox(mode)
{
if(mode!='none')
{
	document.getElementById('txtUrl').value=document.getElementById('selExistingAd').value;

}
else
{
	document.getElementById('txtUrl').value='';
document.getElementById('txtUrl').readOnly=false;
}
	document.getElementById('tdExistingAd').style.display=mode;
}

function show_landingURL(landing_url)
{
	document.getElementById('txtUrl').value=landing_url;
}


function validation()
{

var txtHeadline = document.getElementById("txtHeadline").value;
var txtUrl = document.getElementById("txtUrl").value;


var text_description = document.getElementById("text_description").value; 

if(text_description != "")    {
        document.getElementById("validate_text_description").style.display="none";
    }


if(txtHeadline != "")    {
        document.getElementById("txtHeadline_validate").style.display="none";
    }

if(txtUrl != "")    {
        document.getElementById("txtUrl_validate").style.display="none";
    }


if(txtHeadline == "")    {
        document.getElementById("txtHeadline_validate").style.display="block";
        //document.getElementById("txtHeadline_validate").innerHTML="Please Enter Headline!";
        document.getElementById("txtHeadline").focus();
        return false;
    }


if(text_description == "")    {
        document.getElementById("validate_text_description").style.display="block";
        document.getElementById("validate_text_description").innerHTML="Please Enter Desc!";
        document.getElementById("text_description").focus();
        return false;
    }



if(txtUrl == "")    {
        document.getElementById("txtUrl_validate").style.display="block";
        //document.getElementById("txtUrl_validate").innerHTML="Please Enter Destination Url!";
        document.getElementById("txtUrl").focus();
        return false;
    }

         

   
return true;
}


function preview_heading()
{
document.getElementById("prev_heading").value = document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").innerHTML= document.getElementById("txtHeadline").value;
document.getElementById("prev_heading").style.display = 'block';
}

function preview_text_description_func()
{
document.getElementById("preview_text_description").value = document.getElementById("text_description").value;
document.getElementById("preview_text_description").innerHTML= document.getElementById("text_description").value;
document.getElementById("preview_text_description").style.display = 'block';
}

</script>
<input type="hidden" name="hidAdSpaceId" id="hidAdSpaceId" value="<?php echo $adspaceID;?>">
<input type="hidden" name="hidDelAdSpaceId" id="hidDelAdSpaceId" value="<?php echo $fetFavId[0];?>">
<table cellspacing="0" cellpadding="0" border="0">
  <tr>
    <TD><!--Left TD-->
      <table>
        <TR>
          <TD align="left">&nbsp;</TD>
        </TR>
        <TR>
          <TD align="left"><table style="border:#CCCCCC 1px solid;" cellspacing="0" cellpadding="0">
              <form name="frmAvertise" id="frmAvertise" method="POST" action="advertiser_direct_popup.php?<?php echo $_SERVER["QUERY_STRING"];?>" enctype="multipart/form-data">
                <tr>
                  <td valign="top"><!--LEFT TD-->
                    <table>
                      <input type="hidden" name="fid" id="fid" value="<?php echo $fid;?>">
                      <input type="hidden" name="hidden_field" id="hidden_field" value="www">
                      <input type="hidden" name="enddate" value="<?php echo $_REQUEST[duration];?>">
                      <input type="hidden" name="adspaceid" value="<?php echo $_REQUEST[id];?>">
                      <input type="hidden" var me=this;
name="networkId" value="<?php echo $_REQUEST[network_id];?>">
                      <input type="hidden" name="networkType" value="<?php echo $_REQUEST[network_type];?>">
                      <tr>
                        <td valign="top" align="left"><table cellpadding="5" cellspacing="0" border="0">
                            <tr>
                              <td width="300" class="sitename" colspan="2">Create Your Ad</td>
                            </tr>                            
                            <?php
			 $query_landing_page="select * from adspace_landing_page where UserId='".$_SESSION['siteuserId']."' ";
			$sql_landing_page=mysql_query($query_landing_page);
			$num_landing_page=mysql_num_rows($sql_landing_page);
			if($num_landing_page>0)
			{
 			?>
                            <tr>
                              <TD colspan="2" id="tdExistingAd" style="display:none;">&nbsp;
                                <select name="selExistingAd" id="selExistingAd" onchange="show_landingURL(this.value)">
                                  <?php
						  while($res_landing_page= mysql_fetch_array($sql_landing_page)){
                                    ?>
                                  <option value="<?=$GLOBALS['site_url'].$res_landing_page['pageName'].".php";?>">
                                  <?=stripslashes($res_landing_page['pageName']);?>
                                  </option>
                                  <?
                                        }
                                        ?>
                                </select>
                                <!--left td-->
                              </TD>
                            </tr>
                            <?php
			}
			else
			{
			?>
                            <TD colspan="2" id="tdExistingAd" style="display:none;">&nbsp;
                                You do not have any Landing Pages. <a href="create_landing_page.php" class="register_link">Create a new Landing Page</a> </td>
                              <?php
			}
			?>
                              <?php
								if($_REQUEST['network_type']!='')
								{
								$campaign_network_type=$_REQUEST['network_type'];
								//echo $campaign_network_type;
								}
								else
								{
								$campaign_network_type='text';
								}
								//echo $campaign_network_type;
								if($campaign_network_type=='text' || $campaign_network_type=='thumbnail')
								{ 
								?>
                            <tr>
                              <TD colspan="2"><small>&nbsp;*Headline:</small></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;
                                <input type="text" name="txtHeadline" value="<?php echo $_POST['txtHeadline'];?>" id="txtHeadline" onkeyup="return preview_heading();"></TD>
                              <TD colspan="2" id="txtHeadline_validate" style="display:none;">Please Enter Headline !</TD>
                            </tr>
                            <?php 
							}
							if($campaign_network_type=='text')
							{
							?>
                            <tr>
                              <TD colspan="2"><small>&nbsp;*Add Description</small></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;
                                <textareA name="text_description" id="text_description" onkeyup="return preview_text_description_func();">
                                <?php echo $_POST['text_description'];?>
                                </textareA></TD>
                              <TD colspan="2" id="validate_text_description" style="display:none;">Please Enter Description !</TD>
                            </tr>
                            <?php
							}
							?>
                            <? if($campaign_network_type=='thumbnail' || $campaign_network_type=='banner'){ ?>
                            <tr>
                              <TD colspan="2"><small>&nbsp;*Upload File:  (Max. 90KB) (728x90, 468x60, 120x600, 160x600, 300x250)</small></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">
								<input TYPE='hidden' name='banner_url' value="<?php echo !empty($banner_url) ? $banner_url:$_POST['banner_url'];?>"/>
								<input type="file" name="file" id="file" size='10' />								
								&nbsp;
								<input TYPE='submit' name='upload' value='Upload'/>
								
                                <inpUT type="hidden" name="sahara" value="11">
                              </TD>
                            </tr>
                            <? } ?>
                            <tr>
                              <TD colspan="2"><small>&nbsp;*Destination URL (http://):</small></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;
                                <input type="text" name="txtUrl" id="txtUrl" value="<?php echo $_POST['txtUrl'];?>"></TD>
                              <TD colspan="2" id="txtUrl_validate" style="display:none;">Please Enter Destiny url!</TD>
                            </tr>
                            <tr>
                              <TD colspan="2"><small>&nbsp;Ad Name (For personal reference)</small></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;
                                <input type="text" name="txtAdName" value="<?php echo $_POST['txtAdName'];?>" id="txtAdName"></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;</TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;
                                <input type="button" value="Cancel" name="cancel" id="cancel" onclick="return main_page();">
                                <!--<a href="#" onclick="main_page();">cancel</a>-->
                                &nbsp;
                                <input type="submit" value="Save" name="addtocart" onclick=""></TD>
                            </tr>
                            <tr>
                              <TD colspan="2">&nbsp;</TD>
                            </tr>
                          </table></td>
                        <td width="30px" valign="top"></td>
                        <!--Middle TD-->
                        <td valign="top"><!--Right TD START-->
                          <table>
                            <tr valign="top">
                              <td class="sitename" valign="top" align="center">Preview</td>
                            </tr>
                            <tr>
                              <td align="center" id="prev_heading"></td>
                            </tr>
                            <tr>
                              <td align="center" id="prev_banner">
                              <?php if(!empty($banner_url)||!empty($_POST['banner_url'])):?>
								<a href='javascript:void(0)' id='prev_banner_url' target='_blank'>
									<img src='<?php echo !empty($banner_url) ? $banner_url:$_POST['banner_url'];?>' 
									width='<?php echo $sizeBanner->width? $sizeBanner->width/2.5 :300;?>' height='<?php echo $sizeBanner->height? $sizeBanner->height/2.5 :50;?>' alt='no banner'/>
								</a>
								<?php endif;?>
                              </td>
                            </tr>
                            
                            <tr>
                              <td align="center" id="preview_text_description"></td>
                            </tr>
                            <tr>
                              <td><small>Please note: The Preview will not display correctly if you do not set the "Text size" to "Normal" on your browser.</small></td>
                            </tr>
                          </table></td>
                        <!--Right TD END-->
                      </tr>
                    </table></td>
                </tr>
              </form>
            </table></TD>
      </table></TD>
  </tr>
</table>
</td>
<!-- /ban body part -->
<td class="red_table_RSide"></td>
</tr>
<tr>
  <td><!--<img src="images/red_table_lbottom.jpg" alt="" />--></td>
  <td class="red_table_bottom"></td>
  <td><!--<img src="images/red_table_rbottom.jpg" alt="" />--></td>
</tr>
</table>
</td>
</tr>
</table>
	<script>
	function ad_ads(txtHeadline,text_description,txtUrl,txtAdName)
	{
	
	var xmlHttp;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
		{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
	  catch (e)
		{
		try
		  {
		  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		catch (e)
		  {
		  alert("Your browser does not support AJAX!");
		  return false;
		  }
		}
	  }
	
	
	
	  xmlHttp.open("GET","add_adgroup_ad.php?txtHeadline="+txtHeadline+"&text_description="+text_description+"&txtUrl="+txtUrl+"&txtAdName="+txtAdName,true);
	  xmlHttp.send(null);
	
	
	}	
	</script>